<template>
    <div class="gd-main" style="z-index:100;background-color:rgba(0,0,0,.3);">
        <!-- 具体的操作按钮 -->
        <slot></slot>
        <div id="pdfjs" style="width:100%;height:100%;overflow:auto;"></div>
    </div>
</template>

<script>
    import PDFJS from 'pdfjs-dist';
    import $ from 'jquery';
    
    export default {
        name:'pdfview',
        props: ['pdfurl'],
        watch:{
            pdfurl(){
                this.getPdf();
            }
        },
        data(){
          return{
              pdfFile:null,
              allPage:0
          }
        },
        methods: {
            //获取 pdf 文件
            getPdf(pdfUrl){
                PDFJS.getDocument(this.pdfurl).then(file => {
                    //存储 pdf 文件引用
                    this.pdfFile = file;
                    //存储总页数
                    this.allPage = file.numPages;
                    console.log('file对象 ',file);
                    var html = '';
                    for(var i = 1; i <= this.allPage; i++) {
                        html += '<canvas class="canvas" style="position:relative;left:50%;transform:translateX(-50%);" id="canvas' + i + '"></canvas>';
                    }
                    //添加
                    $('#pdfjs').append(html);
                    setTimeout(() => {
                        this.renderPage(1);    
                    },1000);
                    
               });
            }
            //渲染 pdf 为 canvas
            ,renderPage(pageNum){
                this.pdfFile.getPage(pageNum).then(page => {
                    var canvas = document.getElementById('canvas' + pageNum),
                        ctx = canvas.getContext('2d'),
                        viewport = page.getViewport(2);
                    console.log('文件原始尺寸',viewport);
                    //设置尺寸
                    canvas.width = viewport.width;
                    canvas.height = viewport.height;
                    
                    var renderContext = {
                        canvasContext: ctx,
                        viewport: viewport
                    };
                    
                    page.render(renderContext);
                    
                    //循环一次渲染完
                    if(pageNum < this.allPage){
                        this.renderPage(pageNum + 1);
                    }
                });
            }
        }
    }
</script>
